<template>
  <el-form-item label="高度">
    <el-radio-group v-model="editorForm.height.isDefault" @change="handleDefault">
      <el-radio :label="true">默认</el-radio>
      <el-radio :label="false">自定义</el-radio>
    </el-radio-group>
    <div v-if="!editorForm.height.isDefault" class="custom-after">
      <el-input v-model="editorForm.height.pxValue" @input="getRealValue" />
      <el-tooltip effect="dark" content="请以数字+px或数字+%结尾" placement="right">
        <i class="iconfont">&#xe8c8;</i>
      </el-tooltip>
    </div>
  </el-form-item>
</template>

<script setup>
import { inject, ref, onMounted } from 'vue'
import { pxToRem, checkValue } from '@/utils/tools'

const { editorForm, domList, changeDefault, backUpdate } = inject('commonForm')
// 初始化属性和元素对应关系
const bindDom = ref(new Set())
const initDomMapping = () => {
  const bindKeys = [`${editorForm.value._key}.height.value`]
  domList.value.forEach(element => {
    const bindValue = element.getAttribute('_bind')
    bindKeys.forEach(key => {
      if (bindValue.includes(key)) {
        bindDom.value.add(element)
      }
    })
  })
}

const handleDefault = (val) => {
  if (val) {
    changeDefault('height')
  }
  bindDom.value.forEach(element => {
    element.style.height = editorForm.value.height.value
  })
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

const getRealValue = () => {
  const pass = checkValue(editorForm.value.height.pxValue)
  if (!pass) return
  if (pass === 'px') {
    const pxValue = editorForm.value.height.pxValue.split('px')[0]
    editorForm.value.height.value = pxToRem(pxValue)
  } else {
    editorForm.value.height.value = editorForm.value.height.pxValue
  }
  bindDom.value.forEach(element => {
    element.style.height = editorForm.value.height.value
  })
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

onMounted(() => {
  initDomMapping()
})
</script>

<style lang="scss" scoped></style>